package com.jy.api.shiro.realm;

import com.jy.api.shiro.token.ApiToken;
import com.jy.api.utils.JwtUtils;
import com.jy.framework.exception.MyException;
import com.jy.framework.sys.entity.SysUserEntity;
import com.jy.framework.sys.service.SysUserService;
import com.jy.framework.sys.shiro.ShiroUtils;
import com.jy.framework.sys.shiro.UserRealm;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

/**
 * 自定义Realm 处理登录 权限
 * @author Daved
 */
public class ApiUserRealm extends UserRealm
{
    private static final Logger log = LoggerFactory.getLogger(UserRealm.class);


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JwtUtils jwtUtils;
    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{
        if(token instanceof ApiToken){
            ApiToken authc = (ApiToken) token;
            // 通过绑定信息获取系统用户
            SysUserEntity user = checkToken(authc);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
            return info;
        }
        return super.doGetAuthenticationInfo(token);
    }

    public SysUserEntity checkToken(ApiToken authc) {
        //凭证为空
        if(StringUtils.isBlank(authc.getToken())){
            throw new MyException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        String username = jwtUtils.getUsernameByToken(authc.getToken());
        SysUserEntity  userEntity = sysUserService.selectByUsername(username);
        return userEntity;
    }

}
